from amplitude.controller import Controller

class Account(Controller): 
    actions = ['view', 'edit', 'chgpwd', 'index']
    
    def view(c, req):
        if c.unauthorized(req): return unauthorized(c, req)
        c.setup(req)
        return c.render('/account/view.mako', user=c.user)
    
    index=view

    def edit(c, req):
        if c.unauthorized(req): return unauthorized(c, req)
        c.setup(req)
        if req.env['REQUEST_METHOD']=='POST':
            if req.params.save:
                c.user.set_attribs(prefix='user_', **req.params)
                c.user.update()
                req.session.notice = "Account for %s edited" % (c.user.email)
            else:
                c.response.redirect(c.site_uri+"/account/view")
        return c.render('/account/edit.mako', user=c.user)

    def chgpwd(c, req):
        if c.unauthorized(req): return unauthorized(c, req)
        c.setup(req)
        if req.env['REQUEST_METHOD']=='POST':
            if req.params.save:
                c.user.set_password(req.params.new_password)    
                c.user.update()
                req.session.notice = "Password for %s changed." % (c.user.email)
            else:
                c.response.redirect(c.site_uri+"/account/view")
        return c.render('/account/chgpwd.mako', user=c.user)

    # -- helper methods -- 
    
    def unauthorized(c, req):
        req.init_session()
        if not req.session.has_key('user'):
            return c.response.redirect(c.site_uri+'/user/login?returnpath='+req.uri)

    def setup(c, req):
        c.db = c.db or c.config.connect_to_db()
        c.user = c.models.User(c.db).select_one(email=req.session.user)
        if c.user is None:
            return c.response.redirect(c.site_uri+'/user/login?returnpath='+req.uri)
